package com.digitaleye.dpslite;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.PersistentCookieStore;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;

/**
 * 
 * @author merrickc
 * 
 * contains useful functions for sending info and querying the web server. (ie Logins, registration)
 *
 */
public class WebHelper {
	
	
	Object mLock = new Object();
	
	Context activity;
	
	String tag = "WebServer";
	
	
	public static final String DOMAIN = "downpaymentsaver.com";
	
	static String DPSSERVER = "https://" + DOMAIN + "/dpslite/";
	
	
	DBHelper dbHelper;
	
	AccountDBHelper accountDBHelper;
	
	String errorMessage = "";
	
	
	
	public HttpContext httpContext;
	public static PersistentCookieStore cookieStore;
	

	ProgressDialog progressDialog;
	
	List<Cookie> cookies = null;
	
	
	/**
	 * should the user stay logged in?
	 * value passed by webHelper.login function
	 */
	boolean rememberUser = false;
	
	
	public WebHelper(Context context){
		
		
		
		
		
		this.activity = context;
		
		this.dbHelper = new DBHelper(context);
		
		this.accountDBHelper = new AccountDBHelper(context);
		
		cookieStore = new PersistentCookieStore(this.activity);
		//client.setCookieStore(cookieStore);
        
	}
	
	
	
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
		case Constants.ERROR_DIALOG:
			
			builder = new AlertDialog.Builder(this.activity);
		    // Get the layout inflater

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
			builder.setMessage(this.errorMessage);
		    return builder.create();

			
		}
		
		return null;
	}


	
	
	/** checks if the user has internet **/
	public boolean hasConnection() {
	    ConnectivityManager cm =
	        (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	
	/** gets the devices Unique ID **/
    public String getUDID(){
		final TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);

	    final String tmDevice, tmSerial, androidId;
	    tmDevice = "" + tm.getDeviceId();
	    tmSerial = "" + tm.getSimSerialNumber();
	    androidId = "" + android.provider.Settings.Secure.getString(activity.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);


	    
	    return tmDevice;
    }
	
	
	/**
	 * subscribes the user to the DPS mailing list
	 * @param email the email of the user, given
	 */
	public void subscribe(String email){
		
		class subscribeTask extends AsyncTask<String, Integer, Boolean> {

			Context context;
			
			
			subscribeTask(Context context){
				
				this.context = context;
			}
			
			@Override
	        protected void onPreExecute() {
				super.onPreExecute();
	            
	            
	        }
			
			@Override
			protected Boolean doInBackground(String... params) {

				
				String email = params[0];
				
				
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				
				final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

			    final String tmDevice, tmSerial, androidId;
			    tmDevice = "" + tm.getDeviceId();
			    tmSerial = "" + tm.getSimSerialNumber();
			    androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);


			    
			    
				
		        nameValuePairs.add(new BasicNameValuePair("email", email));
		        
		        nameValuePairs.add(new BasicNameValuePair("udid", tmDevice));
		        
		        
		        HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "/subscribe.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

					
					
					
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

		        

		        return false;

			}
			
			@Override
			public void onProgressUpdate(Integer... progress){

			}
			
			public void onPostExecute(Boolean result){
				
				super.onPostExecute(result);
				
			}

		}
		
		new subscribeTask(this.activity).execute(email);
		
	}
	

	/**
	 * removes user's email from mailing list
	 * @param email
	 */
	public void unsubscribe(String email){
		
		class unsubscribeTask extends AsyncTask<String, Integer, Boolean> {
			
			Context context;
			
			unsubscribeTask(Context context){
				this.context = context;
			}

			@Override
			protected Boolean doInBackground(String... params) {
				
				String email = params[0];
				
				
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				
				final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

			    final String tmDevice, tmSerial, androidId;
			    tmDevice = "" + tm.getDeviceId();
			    tmSerial = "" + tm.getSimSerialNumber();
			    androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);


			    
			    
				
		        nameValuePairs.add(new BasicNameValuePair("email", email));
		        
		        nameValuePairs.add(new BasicNameValuePair("udid", tmDevice));
		        
		        
		        HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "/unsubscribe.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

					
					
					
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

		        

		        return false;
			}
				
		}
		
		new unsubscribeTask(this.activity).execute(email);
		
	}

    	
	
	/**
	 * sends usage data to the web server. 
	 */
	public void updateUsage(){
		

		
		class UpdateUsageTask extends AsyncTask<Void, Integer, Boolean>{
			
			
			Context context;
			
			UpdateUsageTask(Context context){
				this.context = context;
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				/** TO SEND **/
				// number of app Uses
				//uses++ (add to DB on website )
				
				//current amount saved
				int saved = (int) accountDBHelper.getDPSAccountAsAccount().amount;

				
				//down payment goal
				int goal = WebHelper.this.dbHelper.selectGoalTotal();
				
				//total price of desired house
				int homePrice = WebHelper.this.dbHelper.selectHomePrice();
				
				/** TODO add time frame analytic **/
				//time frame in months to save
				//String timeFrame = WebHelper.this.dbHelper.selectGoalDeadline();

			    
				
				
				
			    String udid = WebHelper.this.getUDID();
			    
			    JSONObject json = new JSONObject();
			    

			    try {
				    json.put("udid", udid);
				    json.put("saved", saved);
				    json.put("goal",goal);
					json.put("homePrice", homePrice);
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return false;
				}
			    

		        nameValuePairs.add(new BasicNameValuePair("json", json.toString()));



		        HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "/usage.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}


				
				
				
				return null;
			}
			
		}
		
		new UpdateUsageTask(this.activity).execute();
		
	}
	
	
	/**
	 * sends usage data to the web server. 
	 */
	public void incrementUsage(){
		

		
		class IncrementUsageTask extends AsyncTask<Void, Integer, Boolean>{
			
			
			Context context;
			
			IncrementUsageTask(Context context){
				this.context = context;
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				
				
			    String udid = WebHelper.this.getUDID();
			    

		        nameValuePairs.add(new BasicNameValuePair("udid", udid));



		        HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "/usage.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

		        
				
				
				
				return null;
			}
			
		}
		
		new IncrementUsageTask(this.activity).execute();
		
	}
	
}

